package com.itfitness.openglcamera.render

import android.content.res.AssetManager
import android.graphics.SurfaceTexture
import android.graphics.SurfaceTexture.OnFrameAvailableListener
import android.opengl.GLSurfaceView
import androidx.camera.core.Preview
import androidx.camera.core.Preview.OnPreviewOutputUpdateListener
import androidx.lifecycle.LifecycleOwner
import com.itfitness.openglcamera.helper.CameraHelper
import com.itfitness.openglcamera.widget.CameraView
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10

/**
 *
 * @ProjectName:    OpenGLCamera
 * @Package:        com.itfitness.openglcamera.render
 * @ClassName:      GLRender
 * @Description:     java类作用描述
 * @Author:         itfitness
 * @CreateDate:     2022-12-04 16:01
 * @UpdateUser:     更新者：
 * @UpdateDate:     2022-12-04 16:01
 * @UpdateRemark:   更新说明：
 */
class GLRender : GLSurfaceView.Renderer, OnFrameAvailableListener, OnPreviewOutputUpdateListener{
    init {
        System.loadLibrary("CCOpenGLRender")
    }
    private external fun ndkInitGL(assets: AssetManager)
    private external fun ndkPaintGL(textureId:Int)
    private external fun ndkResizeGL(width:Int,height:Int)
    public external fun ndkRelease()

    private lateinit var textures: IntArray
    private val cameraView:CameraView
    private val cameraHelper:CameraHelper
    private lateinit var surfaceTexture: SurfaceTexture
    constructor(cameraView: CameraView){
        this.cameraView = cameraView
        val lifecycleOwner = cameraView.context as LifecycleOwner
        cameraHelper = CameraHelper(lifecycleOwner,this)
    }

    override fun onSurfaceCreated(p0: GL10?, p1: EGLConfig?) {
        textures = IntArray(1)
        //初始化opengl
        ndkInitGL(cameraView.context.assets)
        //将SurfaceTexture上面的数据用作OpenGL纹理
        surfaceTexture.attachToGLContext(textures[0])
        //新的数据帧有效时的回调接口
        surfaceTexture.setOnFrameAvailableListener(this)
    }

    override fun onSurfaceChanged(p0: GL10?, p1: Int, p2: Int) {
        ndkResizeGL(p1,p2)
    }

    override fun onDrawFrame(p0: GL10?) {
        //更新画面
        surfaceTexture.updateTexImage()
        //opengl渲染
        ndkPaintGL(textures[0])
    }

    override fun onUpdated(output: Preview.PreviewOutput?) {
        //获取预览的surfaceTexture
        surfaceTexture = output!!.surfaceTexture
    }

    override fun onFrameAvailable(p0: SurfaceTexture?) {
        //通知Render进行渲染
        cameraView.requestRender()
    }
}